import type { RouteRecordRaw } from "vue-router";
import type { App } from "vue";
import { createRouter, createWebHashHistory } from "vue-router";
import { useOutUserStore } from "@/store/modules/user";
import Cookies from "js-cookie";
import * as http from "@/request";
import { ElMessage } from "element-plus";
const userStore = useOutUserStore();
const routes: RouteRecordRaw[] = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "login",
    beforeEnter: (to, from, next) => {
      let token = Cookies.get("token");
      token && from.path !== "/" ? next(from) : next();
    },
    component: () => import("@/views/login/index.vue"),
  },
  {
    path: "/home",
    name: "home",
    redirect: "/home/index",
    component: () => import("@/views/home/index.vue"),
    children: [
      {
        path: "index",
        name: "index",
        component: () => import("@/views/index/homepage.vue"),
      },
    ],
  },
];
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

const addRoutes = () => {
  let newMenus = userStore.getMenusConf;
  const routes: RouteRecordRaw[] = [];
  // 获取children递归函数
  const getChildren = (
    curChildren: Menus[] | undefined,
    name: string,
    redirectPath: string
  ): RouteRecordRaw[] => {
    return curChildren && curChildren!.length > 0
      ? curChildren!
          // .filter((item: Menus) => !item.hidden)
          .map((item: Menus) => {
            return {
              path: item.name,
              name: item.name,
              meta: {
                readyRedirectPath:
                  redirectPath + getRedirect(item.children, item.name),
              },
              component: () => import(`@/views/${name}/${item.name}.vue`),
              children: getChildren(
                item.children,
                item.name,
                redirectPath + getRedirect(item.children, item.name)
              ),
            };
          })
      : [];
  };

  const getRedirect = (curChildren: Menus[] | undefined, name: string) => {
    if (!curChildren || curChildren!.length === 0) return "";
    for (const item of curChildren!) {
      if (item.hidden === 0) {
        // 拿到不隐藏的第一个作为重定向的地址
        return "/" + item.name;
      }
    }
  };

  for (const value of Object.values(newMenus)) {
    routes.push({
      path: "/" + value.name,
      name: value.name,
      meta: {
        readyRedirectPath:
          "/" + value.name + getRedirect(value.children, value.name),
      },
      component: () => import(`@/views/home/index.vue`),
      children: getChildren(
        value.children,
        value.name,
        "/" + value.name + getRedirect(value.children, value.name)
      ),
    });
  }
  // 添加路由
  routes.forEach((item) => router.addRoute(item));
};
router.beforeEach(async (to, from, next) => {
  // console.log(to);
  // console.log(from);

  // 防止在没有token下, 重定向导致的死循环
  if (from.path === "/" && to.path === "/login") return next();
  let token = Cookies.get("token");
  let menus = userStore.menus;
  // 登录状态下刷新情况下
  if (token && menus.length === 0) {
    let res = await http.adminInfo();
    if (res.code === 200) {
      userStore.updateMenus(res.data.menus);
      userStore.updateUsername(res.data.username);
      addRoutes();
      return next(to.fullPath);
      // token失效处理
    } else {
      ElMessage({
        message: "登录失效请重新登录",
        type: "error",
      });
      Cookies.remove("token");
      return next("/login");
    }
    // 用户删除token处理, 重新登录
  } else if (!token) {
    ElMessage({
      message: "还未登录,请先登录",
      type: "error",
    });
    next("/login");
    // 正常情况
  } else {
    next();
  }
});

export const initRouter = (app: App<Element>) => {
  app.use(router);
};
